package com.iflytek.springboot_medicine.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TokenFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 打印请求头信息
        log.debug("=== TokenFilter Request Headers ===");
        java.util.Enumeration<String> headerNames = httpRequest.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                log.debug("Header - {}: {}", headerName, httpRequest.getHeader(headerName));
            }
        }

        // 检查 Authorization 头
        String authHeader = httpRequest.getHeader("Authorization");
        log.debug("Authorization header in filter: {}", authHeader);

        // 继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("TokenFilter initialized");
    }

    @Override
    public void destroy() {
        log.info("TokenFilter destroyed");
    }
} 